/*
用法

gulp 一次性编译
gulp watch 动态编译
gulp auto 动态编译并自动刷新

*/

var path = require('path');
var gulp = require('gulp');
var less = require('gulp-less');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var order = require('gulp-order');
var amdOptimize = require("amd-optimize");
var gulpif = require('gulp-if');
var cleanCss = require('gulp-clean-css');
var del = require('del');
var seq = require('gulp-sequence');
var print = require('gulp-print');

var pump = require('pump');

var browserSync = require('browser-sync')
var reload = browserSync.reload


//压缩选项
var con = false;

//构建开始前，用来清除目标位置下的文件
gulp.task('clean', function() {
    return del(['js/dist', 'css']);
})


gulp.task('style', function() {
    return gulp.src([
        './less/style/index.less', './less/assets/*'
    ])
    .pipe(less())
    .pipe(gulpif(con, cleanCss()))
    .pipe(gulp.dest('./css'))
});

//assets
gulp.task('assets', function () {
  return gulp.src('js/src/assets/**')
  .pipe(gulpif(con, uglify()))
  .pipe(gulp.dest('./js/dist/assets/'));
})

// 基础库
gulp.task('basejs', function(cb) {

  pump([
      gulp.src('js/src/base/**'),
      order([
        'jquery.js',
        'util.js',
        'user.js',
        '*.js'
      ]),
      concat('base.js'),
      gulpif(con, uglify()),
      gulp.dest('./js/dist/')
    ],
    cb
  );
});


//业务逻辑
gulp.task('widgetsjs', ['basejs'], function(cb) {

  pump([
      gulp.src('js/src/widgets/**'),
      gulpif(con, uglify()),
      gulp.dest('./js/dist/widgets/')
    ],
    cb
  );
});


//监听修改
gulp.task('watch', ['default'], function() {

  gulp.watch('less/**', ['style']);
  gulp.watch('js/src/base/**', ['basejs']);
  gulp.watch('js/src/widgets/**', ['widgetsjs']);

})

//监听修改并自动刷新
gulp.task('auto', ['default'], function() {

  gulp.watch('less/**', ['style']);
  gulp.watch('js/src/base/**', ['basejs']);
  gulp.watch('js/src/widgets/**', ['widgetsjs']);

    browserSync({
        server: {
            baseDir: './'
        }
    })

    gulp.watch(['*.html', 'css/**', 'js/dist/**', 'html/**'], {cwd: './'}, reload);
})

// seq方法用来控制task的执行顺序
gulp.task('default', seq('clean', ['style', 'assets', 'widgetsjs']));
